/**
 * 数字教材DAT文件解密
 *
 * 需要安装以下依赖:
 * npm install aes-js jszip
 */

const fs = require('fs');
const path = require('path');
const aes = require('aes-js');
const JSZip = require('jszip');
const toolsNode = require('../libs/tools-node');
const KEY256 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];

// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];
let ext = path.extname(from).toLowerCase();
let toDirRoot = path.dirname(from);
let toName = path.basename(from, '.dat');
let to = path.join(toDirRoot, toName);

if (ext === '.dat') {
  let aesCtr = new aes.ModeOfOperation.ctr(KEY256);
  let content = fs.readFileSync(from);
  let decryptedBytes = aesCtr.decrypt(content);
  let zip = new JSZip();
  zip.loadAsync(decryptedBytes).then(() => {
    zip.forEach((relativePath, file) => {
      file.async('string').then((content) => {
        let toFileName = path.join(to, relativePath);
        toolsNode.writeFileSync(toFileName, content);
      })
    });
  });
}
